package lianxi8;

import java.util.ArrayList;
import java.util.List;

/**
 * 观察者
 * @author dell
 *
 */
public class ObserverMain {
	
	public static void main(String[] args) {
		Feed feed= new Feed();
		feed.registerObserver(new NYTimes());
		feed.registerObserver(new Guardian());
		feed.registerObserver(new LeMonde());
		
		feed.notifyObservers(" The queen said her favorite book is Java in action");

		Feed  feedLamdba =new Feed();
		
		feedLamdba.registerObserver((String text)-> {
			if( text != null && text.contains("money")){
				System.out.println("Breaking news in NY! " + text);
			}
		});
		
		feedLamdba.registerObserver((String text)-> {
			if(text != null && text.contains("queen")){
				System.out.println("Yet another news in London..."+ text);
			}
		});
		
		feedLamdba.notifyObservers("Money money money, give me money");
	}
	
	
	interface Observer{
		void inform(String tweet);
	}
	
	interface Subject{
		void registerObserver(Observer o);
		void notifyObservers(String tweet);
	}
	
	static private class NYTimes implements Observer{

		@Override
		public void inform(String tweet) {
			if(tweet != null && tweet.contains("money")){
				System.out.println("Breaking news in NY! "+ tweet);
			}
		}
		
	}
	
	static private class Guardian implements Observer{

		@Override
		public void inform(String tweet) {
			if(tweet != null && tweet.contains("queen")){
				System.out.println("Yet another news in London "+ tweet);
			}
			
		}
		
	}
	
	static private class LeMonde implements Observer{

		@Override
		public void inform(String tweet) {
			if(tweet != null && tweet.contains("wine")){
				System.out.println("Today chesse, wine and news "+ tweet);
			}
			
		}
		
	}
	
	static private class Feed implements Subject{
		private final List<Observer> observers= new ArrayList<>();
		
		@Override
		public void registerObserver(Observer o) {
			this.observers.add(o);
		}

		@Override
		public void notifyObservers(String tweet) {
			observers.forEach(o->o.inform(tweet));
		}
		
	}
}
